import isEmpty from 'loadsh/isEmpty'
import { GetInfoPicture, GetMeetingLogInfo, GetPreviewImage, PostDeleteData, PostInfoPicture, PostMeetingLogInfo } from '/constData/requestFun/_httpRequest';
import { GetMeetingMinutes, GetMeetingMinutesById, GetTopic, GetTopicById, MeetingMinutesDeleteData, PostMeetingMinutes } from '/constData/requestFun/_teseRequest';
import compact from 'loadsh/compact'
import { CORPID, SPACEID } from '/constData/requestFun/_globalData';
Page({
  data: {
    item: 1,
    min: null,
    max: new Date('2033/12/02'),
    defaultDate: new Date(),
    meetinginfo: {
      CorpId: '',//申请人
      MeetingNumber: '',//会议编号
      SummaryName: '', //会议纪要名称
      MeetingDate: '',//开会日期
      MeetingAttachments: '[]',//会议相关附件
      MeetingMinutes: '[]',//会议纪要
      AssociateOtherId: '[]',//关联ID
      Notes: '', //备注
      TempTopic: [],//添加议题
    },
    displayMeetingAttachments: [],
    displayMeetingMinutes: [],
    position: '',
    animation: true,
    basicVisible: false,
    closeVisible: false,
    DisTopicData: [],
    DisTopicDisplayData: [],
    Select2: [{
      value: '总经理办公会',
      label: '总经理办公会'
    },
    {
      value: '支委会',
      label: '支委会'
    },
    {
      value: '董事会',
      label: '董事会'
    },
    {
      value: '股东会',
      label: '股东会'
    }
    ],

  },
  AddTempTopic() {
    const newTempTopic = {
      ApplicatDepart: '综合部', //申请部门
      TopicTitle: '', //议题标题
      TopicContent: '', //议题论述
      ReviewConference: '支委会', //审议会议
      Participants: '', //提请事项
      Notes: '', //备注
    };
    const addnewTempTopic = this.data.meetinginfo.TempTopic.concat([newTempTopic]);
    this.setData({
      meetinginfo: {
        ...this.data.meetinginfo,
        TempTopic: addnewTempTopic
      }
    })
  },
  ApplicatDepartChange(value, e) {
    const TempTopic = this.data.meetinginfo.TempTopic;
    TempTopic[e.currentTarget.dataset.index].ApplicatDepart = value;
    this.setData({
      meetinginfo: {
        ...this.data.meetinginfo,
        TempTopic: TempTopic
      }
    });
  },
  TopicTitleChange(value, e) {
    const TempTopic = this.data.meetinginfo.TempTopic;
    TempTopic[e.currentTarget.dataset.index].TopicTitle = value;
    this.setData({
      meetinginfo: {
        ...this.data.meetinginfo,
        TempTopic: TempTopic
      }
    });
  },
  TopicContentChange(value, e) {
    const TempTopic = this.data.meetinginfo.TempTopic;
    TempTopic[e.currentTarget.dataset.index].TopicContent = value;
    this.setData({
      meetinginfo: {
        ...this.data.meetinginfo,
        TempTopic: TempTopic
      }
    });
  },
  ParticipantsChange(value, e) {
    const TempTopic = this.data.meetinginfo.TempTopic;
    TempTopic[e.currentTarget.dataset.index].Participants = value;
    this.setData({
      meetinginfo: {
        ...this.data.meetinginfo,
        TempTopic: TempTopic
      }
    });
  },
  NotesChange(value, e) {
    const TempTopic = this.data.meetinginfo.TempTopic;
    TempTopic[e.currentTarget.dataset.index].Notes = value;
    this.setData({
      meetinginfo: {
        ...this.data.meetinginfo,
        TempTopic: TempTopic
      }
    });
  },
  onReviewChange(value, e) {
    const TempTopic = this.data.meetinginfo.TempTopic;
    TempTopic[e.currentTarget.dataset.index].ReviewConference = value.join(',');
    this.setData({
      meetinginfo: {
        ...this.data.meetinginfo,
        TempTopic: TempTopic
      }
    });
  },
  DeleteTopic(e) {
    const index = e.currentTarget.dataset.index;
    const addTopic = this.data.meetinginfo.TempTopic.filter((_, i) => i !== index);
    this.setData({
      meetinginfo: {
        ...this.data.meetinginfo,
        TempTopic: addTopic
      }
    })
  },
  Delete(e) {
    const id = e.currentTarget.dataset.id
    MeetingMinutesDeleteData(id, (res) => {
      my.alert({
        title: '撤销成功',
      });
      //刷新数据
      this.setData({
        ReceiveData: this.data.ReceiveData.filter((it) => {
          return it.item1.id !== id
        })
      })
    }, (err) => {
      my.alert({
        title: '撤销失败',
      });
    })
  },
  selectorProject(e) {
    const data = e.target.dataset.data
    const newAssociateOtherIds = [
      ...JSON.parse(this.data.meetinginfo.AssociateOtherId || '[]'), // 将字符串转换为数组，如果为空则使用空数组  
      data.item1.id // 添加新的ID到数组中  
    ];
    this.setData({
      DisTopicDisplayData: [...this.data.DisTopicDisplayData, data],
      meetinginfo: {
        ...this.data.meetinginfo,
        AssociateOtherId: JSON.stringify(newAssociateOtherIds) // 将数组转换回字符串，以符合您当前的数据结构  
      }
    })
   
    my.alert({
      title: '添加成功',
    });
  },
  handlePopupClose() {
    this.setData({
      basicVisible: false,
      scrollVisible: false,
      closeVisible: false,
    });
  },
  handleShowClose() {
    this.setData({ closeVisible: true });
  },
  handleShowBasic(e) {
    var position = e.target.dataset.position;
    this.setData({
      position: position,
      basicVisible: true,
    });
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        GetTopic((res) => {
          const cacheData = res.data.map(it => {
            if (it.item1.corpId === storage.data.result.userid) {
              it.item1['displayAnnex'] = JSON.parse(it.item1.annex)
              return it
            }
          })
          this.setData({
            DisTopicData: compact(cacheData).reverse()
          })
        })
        console.log('DisTopicData', this.data.DisTopicData);
      }
    })
  },

  onNotesChange(date) {
    this.setData({
      meetinginfo: {
        ...this.data.meetinginfo,
        Notes: date
      }
    })
  },
  onSummaryNameChange(date) {
    this.setData({
      meetinginfo: {
        ...this.data.meetinginfo,
        SummaryName: date
      }
    })
  },
  onMeetingNumberChange(date) {
    this.setData({
      meetinginfo: {
        ...this.data.meetinginfo,
        MeetingNumber: date
      }
    })
  },
  handleOk(date, format, e) {
    this.setData({
      meetinginfo: {
        ...this.data.meetinginfo,
        MeetingDate: date
      },
    })
  },
  //获取数据
  onLoad() {
    my.getStorage({
      key: 'userInfo',
      success: (storage) => {
        new Promise((resolve) => {
          GetMeetingMinutes((res) => {
            const cacheData = res.data.map(it => {
              if (it.item1.corpId === storage.data.result.userid) {
                it.item1['displayMeetingAttachments'] = JSON.parse(it.item1.meetingAttachments);
                it.item1['displayMeetingMinutes'] = JSON.parse(it.item1.meetingMinutes);
                it.item1['displayTempTopic'] = JSON.parse(it.item1.tempTopic)
                return it;
              }
            });
            resolve(cacheData);
          });
        }).then((cacheData) => {
          const updatedResPromises = cacheData.map(it => {
            // 将 associateOtherId 从字符串转换为数组，如果是 '[]' 则转换为空数组  
            const associateIds = (typeof it.item1.associateOtherId === 'string' && it.item1.associateOtherId === '[]') ? [] : JSON.parse(it.item1.associateOtherId);
            it.item3 = []
            if (it.item1.corpId === storage.data.result.userid && associateIds.length > 0) {
              // 对每个 associateId 获取 Topic  
              return Promise.all(associateIds.map(associateId => {
                return new Promise((resolve) => {
                  GetTopicById(associateId, (TopicRes) => {
                    it.item3.push(TopicRes.data.item1)
                    resolve(it);
                  });
                });
              })).then(() => it); // 所有 Topic 获取完毕后返回当前对象  
            } else {
              // 如果 associateIds 为空或 it.item1.corpId 不匹配，则直接返回当前对象  
              return Promise.resolve(it);
            }
          });
          // 等待所有 Promise 完成  
          return Promise.all(updatedResPromises).then(updatedRes => {
            this.setData({
              meetinginfo: {
                ...this.data.meetinginfo,
                CorpId: storage.data.result.userid
              },
              ReceiveData: compact(updatedRes).reverse()
            });
          });
        });
      }
    });
  },
  // 上传数据
  onSubmit(e) {
    //上传时，将TempTopic数组转换为字符串
    this.setData({
      meetinginfo: {
        ...this.data.meetinginfo,
        TempTopic: JSON.stringify(this.data.meetinginfo.TempTopic)
      }
    });
    PostMeetingMinutes(JSON.stringify(this.data.meetinginfo),
      (res) => {
        my.getStorage({
          key: 'userInfo',
          success: (storage) => {
            new Promise((resolve) => {
              GetMeetingMinutes((res) => {
                
                const cacheData = res.data.map(it => {
                  if (it.item1.corpId === storage.data.result.userid) {
                    it.item1['displayMeetingAttachments'] = JSON.parse(it.item1.meetingAttachments);
                    it.item1['displayMeetingMinutes'] = JSON.parse(it.item1.meetingMinutes);
                    it.item1['displayTempTopic'] = JSON.parse(it.item1.tempTopic)
                    return it;
                  }
                });
                resolve(cacheData);
              });
            }).then((cacheData) => {
              const updatedResPromises = cacheData.map(it => {
                // 将 associateOtherId 从字符串转换为数组，如果是 '[]' 则转换为空数组  
                const associateIds = (typeof it.item1.associateOtherId === 'string' && it.item1.associateOtherId === '[]') ? [] : JSON.parse(it.item1.associateOtherId);
                it.item3 = []
                if (it.item1.corpId === storage.data.result.userid && associateIds.length > 0) {
                  // 对每个 associateId 获取 Topic  
                  return Promise.all(associateIds.map(associateId => {
                    return new Promise((resolve) => {
                      GetTopicById(associateId, (TopicRes) => {
                        it.item3.push(TopicRes.data.item1)
                        resolve(it);
                      });
                    });
                  })).then(() => it); // 所有 Topic 获取完毕后返回当前对象  
                } else {
                  // 如果 associateIds 为空或 it.item1.corpId 不匹配，则直接返回当前对象  
                  return Promise.resolve(it);
                }
              });
              // 等待所有 Promise 完成  
              return Promise.all(updatedResPromises).then(updatedRes => {
                this.setData({
                  meetinginfo: {
                    ...this.data.meetinginfo,
                    CorpId: storage.data.result.userid
                  },
                  ReceiveData: compact(updatedRes).reverse()
                });
              });
            });
          }
        });
        my.alert({
          title: '提交成功',
        });
        this.setData({
          meetinginfo: {
            ...this.data.meetinginfo,
            MeetingNumber: '',//会议编号
            SummaryName: '', //会议纪要名称
            MeetingDate: '',//开会日期
            MeetingAttachments: '[]',//会议相关附件
            MeetingMinutes: '[]',//会议纪要
            AssociateOtherId: '[]',//关联ID
            Notes: '', //备注
            TempTopic: [],//添加议题
          }
        })
      },
      (err) => {
        my.alert({
          title: '提交成功1',
        });
      })
  },

  //上传图片
  onUpload() {
    let imageMeetingAttachments = ''
    dd.uploadAttachmentToDingTalk({
      image: {
        max: 9,
        spaceId: SPACEID,
        compress: true,
        folderId: '',
        multiple: true,
      },
      types: ['photo'],
      success: (res) => {
        const srcMeetingAttachments = this.data.meetinginfo.MeetingAttachments
        imageMeetingAttachments = res.data
        imageMeetingAttachments.push(...JSON.parse(srcMeetingAttachments))
        this.setData({
          displayMeetingAttachments: imageMeetingAttachments,
          meetinginfo: {
            ...this.data.meetinginfo,
            MeetingAttachments: JSON.stringify(imageMeetingAttachments)
          }
        })
      },
      fail: () => { },
      complete: () => { },
    });
  },
  //上传文件
  onUploadFile() {
    let fileMeetingMinutes = ''
    dd.uploadAttachmentToDingTalk({
      types: ['file'],
      file: { spaceId: SPACEID, max: 9, folderId: '' },
      success: (res) => {
        const srcMeetingMinutes = this.data.meetinginfo.MeetingMinutes
        fileMeetingMinutes = res.data
        fileMeetingMinutes.push(...JSON.parse(srcMeetingMinutes))
        this.setData({
          displayMeetingMinutes: fileMeetingMinutes,
          meetinginfo: {
            ...this.data.meetinginfo,
            MeetingMinutes: JSON.stringify(fileMeetingMinutes)
          }
        })
      },
      fail: () => { },
      complete: () => { },
    });
  },


  PreviewBtn(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },
  CheckPictures(e) {
    const item = e.currentTarget.dataset.item
    dd.previewFileInDingTalk({
      spaceId: item.spaceId,
      fileName: item.fileName,
      corpId: CORPID,
      fileSize: item.fileSize,
      fileType: item.fileType,
      fileId: item.fileId,
    });
  },

});